package cc.mycraft;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

import cc.mycraft.events.MyCraftGlobalEvent;
import cc.mycraft.events.MyCraftResourceBeaconResetEvent;
import cc.mycraft.events.MyCraftTimingEvent;




public class MYCTimer extends JavaPlugin implements Listener{
	
	private static int Second;
	private static int TaskID;
	private static int RBount = 0;
	private static int RBReset;
	private static int GECount = 0;
	private static int GEReset;
	
	@Override
	public void onEnable() {
		saveDefaultConfig();
		Bukkit.getPluginManager().registerEvents(this, this);
		Second = getConfig().getInt("TimingSecond");
		startTimer();
		super.onEnable();
	}

	@Override
	public void onDisable() {
		Bukkit.getScheduler().cancelTasks(this);
		super.onDisable();
	}
	
	public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
		label = label.toLowerCase();
		switch (label) {
		case "tmreload":
			reloadConfig();
			Second = getConfig().getInt("TimingSecond");
			Bukkit.getScheduler().cancelTask(TaskID);
			startTimer();
			return true;
		case "calltimer":
			callTimer();
			return true;
		default: return true;
		}
	}
	
	private void startTimer() {
		RBReset = 7200/Second;
		GEReset = 1200/Second;
		TaskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
			@Override
			public void run() {
				callTimer();
			}
		}, 100l, Second*20l);
	}
	
	private void callTimer() {
		RBount++;
		GECount++;
		if(RBount>=RBReset) {
			Bukkit.getPluginManager().callEvent(new MyCraftResourceBeaconResetEvent(MYCPlugin.TIMER));
			RBount=0;
		}
		if(GECount>=GEReset) {
			Bukkit.getPluginManager().callEvent(new MyCraftGlobalEvent(MYCPlugin.TIMER,false));
			GECount=0;
		}
		Bukkit.getPluginManager().callEvent(new MyCraftTimingEvent(MYCPlugin.TIMER));
	}

}

